package com.example.zuelweb.service.impl;

import com.example.zuelweb.service.PyRcongnizeService;
import org.springframework.stereotype.Service;

import okhttp3.*;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.*;
import java.io.File;
import java.io.IOException;

@Service
public class PyRcongnize implements PyRcongnizeService {


    @Override
    public String pyrecognize(String filename) {
        // 文件路径和URL
        String filePath = "E:\\Study\\Java\\JavaWeb_Zuel\\zuel-web\\src\\main\\resources\\static\\upload\\" + filename;
        String url = "http:localhost:5000/predict";

        // 构造OkHttpClient对象
        OkHttpClient client = new OkHttpClient();

        // 构造Request对象
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "file.jpg",
                        RequestBody.create(MediaType.parse("image/jpeg"), new File(filePath)))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        try(Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();

            Gson gson = new Gson();
            Map<String, Object> map = new HashMap<String, Object>();
            map = gson.fromJson(responseBody, map.getClass());

            List<Map<String, Object>> predictions = (List<Map<String, Object>>) map.get("predictions");

            String result = (String)predictions.get(0).get("label");
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }

        return "服务器出错！！！";
    }

}
